//
//  CSCreateController.m
//  CreateWithSuper
//
//  Created by chenjunbo on 2024/6/1.
//  Copyright © 2024 CS. All rights reserved.
//

#import "CSCreateController.h"

#import "CSFirstInPopController.h"
#import "CSCreatingVC.h"
#import "CSNetworkHelper.h"
#import "CSConnectStatusController.h"
#import "ADModule.h"
#import "SVProgressHUD.h"
#import "CSHomeImgCell.h"
#import "CSHomeSave.h"

@interface CSCreateController ()<UITextViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *textViewCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *textViewPLabel;

@property (nonatomic, strong) NSArray *defaultLuckArr;

@property (nonatomic, strong) NSString *lastRandomStr;
@property (weak, nonatomic) IBOutlet UIImageView *vpnStatusImgView;
@property (weak, nonatomic) IBOutlet UIButton *connectBtn;

@property (nonatomic, strong) NSTimer *conTimer;
@property (nonatomic, assign) NSInteger loadTime;

@property (weak, nonatomic) IBOutlet UIView *navAdView;


@property (weak, nonatomic) IBOutlet UIImageView *tabbarHomeImg;
@property (weak, nonatomic) IBOutlet UILabel *tabbarhomeLabel;

@property (weak, nonatomic) IBOutlet UIImageView *tabbarAvatarsImg;
@property (weak, nonatomic) IBOutlet UILabel *tabbarAvatarsLabel;

@property (weak, nonatomic) IBOutlet UIView *guideSwipeView;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (weak, nonatomic) IBOutlet UIButton *leftBtn;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;
@property (weak, nonatomic) IBOutlet UIButton *goodBtn;
@property (weak, nonatomic) IBOutlet UIView *imgView;

@property (nonatomic, assign) NSInteger scrollCount;
@property (weak, nonatomic) IBOutlet UIView *imgNavView;

@end

@implementation CSCreateController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"FirstInHome"] == true){
        if ([[ADModule standardInstance]haveNavAd]){
            self.navAdView.hidden = false;
            [[ADModule standardInstance]showNavAd:self.navAdView];
        }else{
            
        }
    }
    
}

- (IBAction)hideAction:(id)sender {
    self.guideSwipeView.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    // Do any additional setup after loading the view.
    self.scrollCount = 0;
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"CSHomeImgCell" bundle:nil] forCellWithReuseIdentifier:@"CSHomeImgCell"];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(250, 250);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.collectionViewLayout = layout;
    
    NSMutableArray *imageAndIndexArray = [NSMutableArray arrayWithCapacity:39];
    for (int i = 1; i < 39; i++) {
        NSString *imageStr = [NSString stringWithFormat:@"image%d",i];
        [imageAndIndexArray addObject:imageStr];
    }
    
    NSMutableArray *newArray = [NSMutableArray arrayWithArray:imageAndIndexArray];

    for(int i = 0; i< 38; i++){
        int m = (arc4random() % (38 - i)) + i;
        [newArray exchangeObjectAtIndex:i withObjectAtIndex: m];
    }
    
    self.dataArr = newArray;
    self.loadTime = 0;
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    

    
    NSInteger wordshow = [ADModule standardInstance].wordshow;
  
    bool showIntOrNav = [ADModule standardInstance].showIntOrNav;
    
    if (wordshow == 1){
        self.defaultLuckArr = @[@"Sexy beauty",@"Car sex",@"Kitchen sex",@"Sexual violence"];
    }else{
        self.defaultLuckArr = @[@"Mystery castle",@"Sexy cat",@"Dream forest",@"Future car",@"Enchantment spirit"];
    } 
    
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"FirstInHome"]){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"FirstInHome"];

            CSFirstInPopController *popView = [[CSFirstInPopController alloc]init];
            popView.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self presentViewController:popView animated:NO completion:nil];

            UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
            view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
            [[UIApplication sharedApplication].keyWindow addSubview:view];
            
            popView.leftBlock = ^{
                
                [view removeFromSuperview];
                
                if (showIntOrNav){
                    [popView dismissViewControllerAnimated:NO completion:nil];
                }

                [[ADModule standardInstance]showInterAdWithVC:self dismiss:^{
                    if (!showIntOrNav){
                        [popView dismissViewControllerAnimated:NO completion:nil];
                    }
                    [self try];
                }];

            };
            
            popView.rightBlock = ^(NSString * _Nonnull text) {

                if (text.length > 0){

                    [view removeFromSuperview];
                    if (showIntOrNav){
                        [popView dismissViewControllerAnimated:NO completion:nil];
                    }
                    
                    [[ADModule standardInstance]showInterAdWithVC:self dismiss:^{
                        if (!showIntOrNav){
                            [popView dismissViewControllerAnimated:NO completion:nil];
                        }
                        [self create:text];
                    }];
                }else{
                    [view removeFromSuperview];
                    
                    if (showIntOrNav){
                        [popView dismissViewControllerAnimated:NO completion:nil];
                    }

                    [[ADModule standardInstance]showInterAdWithVC:self dismiss:^{
                        if (!showIntOrNav){
                            [popView dismissViewControllerAnimated:NO completion:nil];
                        }
                        [self try];
                    }];
                }
            };
        });

    }

}

- (IBAction)goodClick:(id)sender {
    [self.goodBtn setImage:[UIImage imageNamed:@"like_sel"] forState:UIControlStateNormal];
}

- (IBAction)saveClick:(id)sender {
    
    [[ADModule standardInstance]showInterAdWithVC:self dismiss:^{
        NSInteger current = [self getCurrentVisibleIndexPath];
        UIImage *img = [UIImage imageNamed: self.dataArr[current]];
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];

}

-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil;
    if(error){
        
        NSURL *url1 = [NSURL URLWithString:@"App-Prefs:root=Photos"];
        NSURL *url2 = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if (@available(iOS 11.0, *)) {
            if ([[UIApplication sharedApplication] canOpenURL:url2]){
                [[UIApplication sharedApplication] openURL:url2 options:@{} completionHandler:nil];
            }
        } else {
            if ([[UIApplication sharedApplication] canOpenURL:url1]){
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:url1 options:@{} completionHandler:nil];
                } else {
                    [[UIApplication sharedApplication] openURL:url1];
                }
            }
        }

    }else{

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Create" bundle:nil];
        CSHomeSave *vc = [storyboard instantiateViewControllerWithIdentifier:@"CSHomeSave"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (IBAction)homeTabbarClick:(id)sender {
    
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"FirstInHome"] == true){
        if ([[ADModule standardInstance]haveNavAd]){
            self.navAdView.hidden = false;
            [[ADModule standardInstance]showNavAd:self.navAdView];
        }else{
            
        }
    }
    
    [self.tabbarHomeImg setImage:[UIImage imageNamed:@"home_01"]];
    self.tabbarhomeLabel.textColor = [UIColor blackColor];
    
    [self.tabbarAvatarsImg setImage:[UIImage imageNamed:@"avatars_02"]];
    self.tabbarAvatarsLabel.textColor = [UIColor grayColor];
    
    self.imgView.hidden = YES;
}

- (IBAction)avatarsTabbarClick:(id)sender {
    self.scrollCount = 0;
    if ([[ADModule standardInstance]haveNavAd]){
        self.imgNavView.hidden = false;
        [[ADModule standardInstance]showNavAd:self.imgNavView];
    }else{
        
    }
    
    [self.tabbarHomeImg setImage:[UIImage imageNamed:@"home_02"]];
    self.tabbarhomeLabel.textColor = [UIColor grayColor];
    
    [self.tabbarAvatarsImg setImage:[UIImage imageNamed:@"avatars_01"]];
    self.tabbarAvatarsLabel.textColor = [UIColor blackColor];
    self.imgView.hidden = NO;
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"FirstInGuideSwipeView"]){
        self.guideSwipeView.hidden = NO;
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"FirstInGuideSwipeView"];
    }
}

- (IBAction)connectClick:(UIButton *)sender {

    
}

- (IBAction)clearallClick:(UIButton *)sender {
    self.textView.text = @"";
    self.textViewCountLabel.text = @"0/102";
}

- (IBAction)tryClick:(UIButton *)sender {
    [self try];
}

- (void)try{
    NSString *randomStr = [self randomStr];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Create" bundle:nil];
    CSCreatingVC *vc = [storyboard instantiateViewControllerWithIdentifier:@"CSCreatingVC"];
    vc.taskID = @"";
    vc.createStr = randomStr;
    vc.isLocal = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)create:(NSString *)textViewStr{
    
    if (textViewStr.length == 0){
        [SVProgressHUD showErrorWithStatus:@"Please enter a description"];
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
        dispatch_after(delay, dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    [self.view endEditing:YES];
    
    [[CSNetworkHelper standardInstance]requestTxt2img:textViewStr callback:^(NSString * _Nonnull result) {
        
        if (result.length > 0){
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Create" bundle:nil];
            CSCreatingVC *vc = [storyboard instantiateViewControllerWithIdentifier:@"CSCreatingVC"];
            vc.taskID = result;
            vc.createStr = textViewStr;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }];
}

- (IBAction)createClick:(UIButton *)sender {
    
    [self create:self.textView.text];
    
}

- (NSString *)randomStr {

    NSString *randomStr = self.defaultLuckArr[arc4random_uniform(self.defaultLuckArr.count)];
    
    if ([randomStr isEqualToString:self.lastRandomStr]){
        return [self randomStr];
    } else {
        self.lastRandomStr = randomStr;
        return randomStr;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.textView endEditing:YES];
}

- (void)textViewDidChange:(UITextView *)textView {
    
    self.textViewCountLabel.text = [NSString stringWithFormat:@"%lu/102",(unsigned long)textView.text.length];
    
    if (textView.text.length > 0){
        self.textViewPLabel.hidden = YES;
    }else{
        self.textViewPLabel.hidden = NO;
    }
    
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSUInteger newTextLength = [textView.text length] + [text length] - range.length;
    if (newTextLength > 102) {
        return NO;
    }
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}
 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CSHomeImgCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CSHomeImgCell" forIndexPath:indexPath];
    cell.imgView.image = [UIImage imageNamed:self.dataArr[indexPath.row]];
    return cell;
}

- (IBAction)leftAction:(UIButton *)sender {
    NSInteger current = [self getCurrentVisibleIndexPath];
    if(current != 0){
        [self scrollToIndex:current - 1];
        self.scrollCount ++;
        
        if (self.scrollCount == 3){
            [[ADModule standardInstance]showInterAdWithVC:self dismiss:^{
                
            }];
            self.scrollCount = 0;
        }
    }
}

- (IBAction)rightAction:(UIButton *)sender {
    NSInteger current = [self getCurrentVisibleIndexPath];
    if(current != self.dataArr.count - 1){
        [self scrollToIndex:current + 1];
        
        self.scrollCount ++;
        
        if (self.scrollCount == 3){
            [[ADModule standardInstance]showInterAdWithVC:self dismiss:^{
                
            }];
            self.scrollCount = 0;
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.scrollCount ++;

    if (self.scrollCount == 3){
        [[ADModule standardInstance]showInterAdWithVC:self dismiss:^{
            
        }];
        self.scrollCount = 0;
    }
    [self.goodBtn setImage:[UIImage imageNamed:@"like_nor"] forState:UIControlStateNormal];
    
    NSInteger current = [self getCurrentVisibleIndexPath];

    if (current == 0){
        [self.leftBtn setImage:[UIImage imageNamed:@"icon_previous_02"] forState:UIControlStateNormal];
        self.leftBtn.enabled = NO;
    }else{
        [self.leftBtn setImage:[UIImage imageNamed:@"icon_previous_01"] forState:UIControlStateNormal];
        self.leftBtn.enabled = YES;
    }
    if (current == self.dataArr.count - 1){
        [self.rightBtn setImage:[UIImage imageNamed:@"icon_next-02"] forState:UIControlStateNormal];
        self.rightBtn.enabled = NO;
    }else{
        [self.rightBtn setImage:[UIImage imageNamed:@"icon_next-01"] forState:UIControlStateNormal];
        self.rightBtn.enabled = YES;
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {

    self.scrollCount ++;

    if (self.scrollCount == 3){
        [[ADModule standardInstance]showInterAdWithVC:self dismiss:^{
            
        }];
        self.scrollCount = 0;
    }
    
    NSInteger current = [self getCurrentVisibleIndexPath];

    if (current == 0){
        [self.leftBtn setImage:[UIImage imageNamed:@"icon_previous_02"] forState:UIControlStateNormal];
        self.leftBtn.enabled = NO;
    }else{
        [self.leftBtn setImage:[UIImage imageNamed:@"icon_previous_01"] forState:UIControlStateNormal];
        self.leftBtn.enabled = YES;
    }
    if (current == self.dataArr.count - 1){
        [self.rightBtn setImage:[UIImage imageNamed:@"icon_next-02"] forState:UIControlStateNormal];
        self.rightBtn.enabled = NO;
    }else{
        [self.rightBtn setImage:[UIImage imageNamed:@"icon_next-01"] forState:UIControlStateNormal];
        self.rightBtn.enabled = YES;
    }
    
    
}

- (NSInteger)getCurrentVisibleIndexPath {
    NSArray *indexPaths = [self.collectionView indexPathsForVisibleItems];
    if (!indexPaths.count) {
        return nil;
    }
    NSIndexPath *current = indexPaths.firstObject;
    return current.row;
}

- (void)scrollToIndex:(NSInteger)index {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    
    if (indexPath != nil) {
        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}
@end
